package com.tyc.aqs;

import java.util.concurrent.locks.StampedLock;

/**
 * 没有使用AQS java1.8才开始有
 *
 * 将读分为了乐观读、与悲观读
 */
public class StampLock {
    private final StampedLock stampedLock = new StampedLock();
    private double x;
    private double y;
    public void move(double deltaX, double deltaY){
        long stamp = stampedLock.writeLock();
        try {
            x+=deltaX;
            y+=deltaY;
        } finally {
            stampedLock.unlockWrite(stamp);
        }
    }

    public double distanceFromOrigin(){
        //获取乐观读锁 允许其他线程写
        long stamp = stampedLock.tryOptimisticRead();
        double currentX = x;
        double currentY = y;
        //判断获取乐观锁后是否有其他线程写(验证版本号)
        //如果有采用悲观读 重新获取值
        if(!stampedLock.validate(stamp)){
            stamp = stampedLock.readLock();
            try {
                currentX = x;
                currentY = y;
            } finally {
                stampedLock.unlockRead(stamp);
            }
        }
        return Math.sqrt(currentX * currentX + currentY * currentY);
    }
}
